package wymiana.spring;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;

public class LoggingFilter implements Filter {

    private final Logger logger = Logger.getLogger(getClass());

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String txName = "GUI:" + httpRequest.getServletPath();
        logger.info("Request: " + txName);

        try {
            chain.doFilter(request, response);

        } catch (Throwable ex) {
            int httpstatus;

            if (ex instanceof org.springframework.web.util.NestedServletException && ex.getCause()!=null) {
                ex = ex.getCause();
            }

            if (ex instanceof MissingServletRequestParameterException
                    || ex instanceof TypeMismatchException
                    || ex instanceof ServletRequestBindingException) {
                httpstatus = HttpServletResponse.SC_BAD_REQUEST;
                logger.warn("MAC400:" + ex.getMessage());

            } else if (ex instanceof AccessDeniedException) {
                httpstatus = HttpServletResponse.SC_FORBIDDEN;

            } else {
            	httpstatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                logger.error(ex, ex);
            }

            try {
                ((HttpServletResponse) response).sendError(httpstatus);
            } catch (IOException ioex) {
                logger.error("ERROR: Could not send error status", ex);
            }
        }
    }
}
